package com.example.service.Impl;
import com.example.common.constant.MessageConstant;
import com.example.common.exception.AccountException;
import com.example.common.exception.BaseException;
import com.example.common.exception.NotRegisterException;
import com.example.common.exception.PasswordErrorException;
import com.example.entity.User;
import com.example.entity.dto.UserDto;
import com.example.mapper.UserMapper;
import com.example.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import static com.example.common.constant.PasswordConstant.DEFAULT_PASSWORD;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private UserMapper userMapper;


    // 使用spring-security进行密码加密
    BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(12);

    /**
     * 用户登录
     * @param userDto
     * @return
     */
    public User loginUser(UserDto userDto) {
        System.out.println(encoder.encode("1"));
        User existingUser = userMapper.findByUsername(userDto.getAccount());
        if (existingUser != null ) {
            //登录成功
            if (encoder.matches(userDto.getPassword(), existingUser.getPassword())){
                return existingUser;
            }
            //密码错误
            else {
                throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
            }
        }
        //未注册
        else
            throw new NotRegisterException(MessageConstant.ACCOUNT_NOT_FOUND);
    }
    /**
     * 重置密码
     * @param userDto
     */
    public void resetPassword(UserDto userDto) {
        User existingUser = userMapper.findByUsername(userDto.getAccount());
        if (existingUser == null) {
            throw new AccountException(MessageConstant.ACCOUNT_NOT_FOUND);
        }
        String pwd = encoder.encode(DEFAULT_PASSWORD);
        existingUser.setPassword(pwd);
        userMapper.update(existingUser);
    }

    /**
     * 修改密码
     * @param userDto
     * @param password
     */
    public void changePassword(UserDto userDto, String password) {
        User existingUser = userMapper.findByUsername(userDto.getAccount());
        if (existingUser == null) {
            throw new AccountException(MessageConstant.ACCOUNT_NOT_FOUND);
        }
        if (encoder.matches(userDto.getPassword(), existingUser.getPassword())){
            String pwd = encoder.encode(password);
            existingUser.setPassword(pwd);
            userMapper.update(existingUser);
        }else {
            throw new BaseException(MessageConstant.PASSWORD_ERROR);
        }
    }
}
